/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package vadung.contragame2d;

import java.io.IOException;
import java.io.InputStream;
import javax.microedition.lcdui.Graphics;
import javax.microedition.lcdui.Image;
import sample_1.Scanner;

   
/**
 *
 * @author dung.voanh
 */
public final class ResourceManager {
    // Instance ResourceManager
    private static ResourceManager s_resourceManager;
    // ALl images
    public static Image[] s_aimgRes;
    // All Sprite
    public static MySprite[] s_asprRes;
    // All String path sound
    public static Object[] s_aSoundRes;
    
    public static ResourceManager GetInstance(){
        if(s_resourceManager == null){
            s_resourceManager = new ResourceManager();
        }
        return s_resourceManager;
    }
    
    public Image GetImage(int IMAGE_ID){
        if(IMAGE_ID >= 0 && IMAGE_ID < s_aimgRes.length){
            return s_aimgRes[IMAGE_ID];
        }
        return null;
    }
    
//    public MySprite GetSprite(int SPRITE_ID){
//        if(SPRITE_ID >= 0 && SPRITE_ID < s_asprRes.length){
//            return s_asprRes[SPRITE_ID];
//        }
//        return null;
//    }
    
    public MySprite GetSprite(int iSprite_ID){
        for(int i = 0; i < s_asprRes.length; i++){
            if(s_asprRes[i].GetID() == iSprite_ID)
                return new MySprite(s_asprRes[i]);
        }
        return null;
    }
    
    public MySprite GetSprite(String strSpriteName){
        for(int i = 0; i < s_asprRes.length; i++){
            if(s_asprRes[i].GetName().equalsIgnoreCase(strSpriteName))
                return new MySprite(s_asprRes[i]);
        }
        return null;
    }
    
    public Object GetSound(int SOUND_ID){
        if(SOUND_ID >= 0 && SOUND_ID < s_aSoundRes.length){
            return s_aSoundRes[SOUND_ID];
        }
        return null;
    }
    
    private ResourceManager() {
        Init();
    }
    
    private void Init() {
        
    }    
    
    public void Load(String file){
        // Delete old memory
        s_aSoundRes = null;
        s_aimgRes = null;
        s_asprRes = null;
        //Loade new memory
        InputStream inputStream = getClass().getResourceAsStream(file);
        Scanner scanner = new Scanner(inputStream);
        String strElement = ""; 
        while(scanner.hasNext()){
            try {
                if(strElement.equalsIgnoreCase("#IMAGES")){
                    // Get path of element image
                    strElement = LoadImages(scanner);                    
                
                }else if(strElement.equalsIgnoreCase("#SPRITES")){
                    // Get sprite element image
                    strElement = LoadSprites(scanner);   
                
                }else if(strElement.equalsIgnoreCase("#SOUNDS")){
                    strElement = LoadPathSounds(scanner);
                                        
                }else{
                    strElement = "";
                }
                
                if(strElement.equals("")){
                    strElement = scanner.getNext();
                }
                
            } catch (IOException ex) {                
                System.out.println(ex.getMessage());
            }catch (Exception e){ 
                System.out.println(e.getMessage());                
            }
        }
        
         //Init values for sprites
         for(int i = 0; i < s_asprRes.length; i++){
             s_asprRes[i].Init();
         }
    }
         
    private Image LoadImage(String path) { 
        Image imgResult = null;
        try {
            imgResult =  Image.createImage(path);
            System.out.println("SUCCESS: RES load image - " + path);
        } catch (IOException ex) {
            System.out.println("ERROR: RES load image - " + path);
        }
        return imgResult;
    }  
     
    /**
     * Load all images in resource
     * @param scanner: Use read node element in text file
     * @return : String element is end read last
     * @throws Exception 
     */
    private String LoadImages(Scanner scanner) throws Exception{
        System.out.println("LOAD: RES Images...");
        String strElement = "";
        int iNumberOfElement;
        try {
            // Get path of element image
            iNumberOfElement = scanner.getNextInt();
            s_aimgRes = new Image[iNumberOfElement];
        } catch (IOException ex) {
            throw new Exception("ERROR: RES image load number of elements.");            
        }
        
        int iIndex = -1;
         while(iIndex < iNumberOfElement && scanner.hasNext()){
            try {
                strElement = scanner.getNext();
                if(strElement.startsWith("#")){
                    break; //End read images
                    
                }else if(strElement.equalsIgnoreCase("PATH")){                   
                    iIndex++; //New path element
                    
                }else{
                    s_aimgRes[iIndex] = LoadImage(strElement);
                }                
            } catch (IOException ex) {                
                System.out.println(ex.getMessage());
            }
         }
         return strElement;
    } 
    
    /**
     * Load all Sprites in resource
     * @param scanner: Use read node element in text file
     * @return : String element is end read last
     * @throws Exception 
     */
    private String LoadSprites(Scanner scanner) throws Exception{
        System.out.println("LOAD: RES Sprites...");
        String strElement = "";
        int iNumberOfElement;
        try {
            // Get path of element image
            iNumberOfElement = scanner.getNextInt();
            s_asprRes = new MySprite[iNumberOfElement];
        } catch (IOException ex) {
            throw new Exception("ERROR: RES load number of sprite elements.");
            
        }
        int iIndex = -1;
         while(iIndex < iNumberOfElement && scanner.hasNext()){
            try {
                strElement = scanner.getNext();
                
                if(strElement.startsWith("#")){
                    break; //End read sprites
                }else if(strElement.equalsIgnoreCase("ID")){  //Element ID must on top in all attribute                  
                    iIndex++;//New sprite element
                    int id = scanner.getNextInt();
                    s_asprRes[iIndex] = new MySprite();
                    s_asprRes[iIndex].SetID(id);
                    System.out.println("LOAD: RES load new sprite: " + id);
                    
                } else if(strElement.equalsIgnoreCase("NAME")){   
                    s_asprRes[iIndex].SetName(scanner.getNext());
                    
                } else if(strElement.equalsIgnoreCase("IMAGE_ID")){ 
                    s_asprRes[iIndex].SetImageID(scanner.getNextInt());
                    
                } else if(strElement.equalsIgnoreCase("FRAME_TOTAL")){ 
                    s_asprRes[iIndex].SetTotalFrame(scanner.getNextInt());
                    
                }  else if(strElement.equalsIgnoreCase("STATE_TOTAL")){ 
                    s_asprRes[iIndex].SetTotalState(scanner.getNextInt());
                    
                }                
            } catch (IOException ex) {                
                System.out.println("ERROR: RES load Sprite.\n" + ex.getMessage());
            }
         }
         return strElement;
    }
    
    /**
     * Load all string Sound's path in resource
     * @param scanner: Use read node element in text file
     * @return : String element is end read last
     * @throws Exception 
     */
    private String LoadPathSounds(Scanner scanner) throws Exception{
        System.out.println("LOAD: RES Sounds...");
        String strElement = "";
        int iNumberOfElement;
        try {
            // Get path of element image
            iNumberOfElement = scanner.getNextInt();
            s_aSoundRes = new String[iNumberOfElement];
        } catch (IOException ex) {
            throw new Exception("ERROR: RES Sounds load number elements.");            
        }
        
        int iIndex = -1;
         while(iIndex < iNumberOfElement && scanner.hasNext()){
            try {
                strElement = scanner.getNext();
                if(strElement.startsWith("#")){
                    break; //End read images
                    
                }else if(strElement.equalsIgnoreCase("PATH")){                   
                    iIndex++; //New path element
                    
                }else{
                    s_aSoundRes[iIndex] = strElement;
                    System.out.println("SUCCESS: RES load path sound - " + strElement);
                }                
            } catch (IOException ex) {                
                System.out.println(ex.getMessage());
            }
         }
         return strElement;
    } 
    
    
     //--------------------------------------------------------------------------//
    //-source http://www.oracle.com/technetwork/java/image-resizing-137933.html-//
    //--------------------------------------------------------------------------//
    /* This methog resizes an image by resampling its pixels
    * @param src The image to be resized
    * @return The resized image
    */
    public static Image ResizeImage(Image src, int screenWidth, int screenHeight) {
        int srcWidth = src.getWidth();
        int srcHeight = src.getHeight();
        Image tmp = Image.createImage(screenWidth, srcHeight);
        Graphics g = tmp.getGraphics();
        int ratio = (srcWidth << 16) / screenWidth;
        int pos = ratio/2;

        //Horizontal Resize        

        for (int x = 0; x < screenWidth; x++) {
            g.setClip(x, 0, 1, srcHeight);
            g.drawImage(src, x - (pos >> 16), 0, Graphics.LEFT | Graphics.TOP);
            pos += ratio;
        }

        Image resizedImage = Image.createImage(screenWidth, screenHeight);
        g = resizedImage.getGraphics();
        ratio = (srcHeight << 16) / screenHeight;
        pos = ratio/2;        

        //Vertical resize

        for (int y = 0; y < screenHeight; y++) {
            g.setClip(0, y, screenWidth, 1);
            g.drawImage(tmp, 0, y - (pos >> 16), Graphics.LEFT | Graphics.TOP);
            pos += ratio;
        }
        return resizedImage;

    }//resize image 

}
